package com.project.weimi.utils;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;

import com.project.weimi.entity.response.City;
import com.project.weimi.entity.response.District;
import com.project.weimi.entity.response.Province;

public class XmlPullInflateUtil {

	public static List<Province> xmlPullInflate(InputStream is) throws Exception{
		List<Province> list = null;
		Province p = null;
		City c = null;
		District d = null;
		
		XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
		XmlPullParser parser = factory.newPullParser();
		parser.setInput(is, "utf-8");
		int type = parser.getEventType();
		while (type != XmlPullParser.END_DOCUMENT) {
			switch (type) {
			case XmlPullParser.START_DOCUMENT:
				list = new ArrayList<Province>();
				
				break;
			case XmlPullParser.START_TAG:
				if(parser.getName().equals("province")){
					p = new Province();
					p.setName(parser.getAttributeValue(0));
					p.setCityList(new ArrayList<City>());
				}
				else if(parser.getName().equals("city")){
					c = new City();
					c.setName(parser.getAttributeValue(0));
					c.setDistrictList(new ArrayList<District>());
				}
				else if(parser.getName().equals("district")){
					d = new District();
					d.setName(parser.getAttributeValue(0));
					d.setZipcode(parser.getAttributeValue(1));
				}
				
				break;
			case XmlPullParser.END_TAG:
				if(parser.getName().equals("district")){
					c.getDistrictList().add(d);
				}
				else if(parser.getName().equals("city")){
					p.getCityList().add(c);
				}
				else if(parser.getName().equals("province")){
					list.add(p);
				}
				break;
			default: 
				break;
			}
			type = parser.next();
		}
		return list;
	}
	
}
